<template>

    <div>
        <x-button>状态:{{userStatus}}</x-button>
        <x-button v-if="userStatus == status.__init" @click.native="set">开启</x-button>
        <!--<x-button @click.native="test">测试</x-button>-->
        <!--<cell title="测试" is-link link="/user/pay">测试</cell>-->
        <div v-if="userStatus === status.__set">
            <x-input title="奖品名称" v-model="prize"></x-input>
            <!--<x-input title="中奖人数" v-model="luck_num"></x-input>-->
            <!--<x-input title="参与条件" v-model="setting.price"></x-input>-->
            <x-number title="中奖人数" :min="1" :max="100" value="1" v-model="luck_num" fillable></x-number>
            <x-number title="参与条件(金额)" :min="1" :max="100" value="1" v-model="price" fillable></x-number>
            <!--<input name="a" type="radio" v-model="setting.luck_time" value="3">3分钟
            <input name="a" type="radio" v-model="setting.luck_time" value="5">5分钟-->
            <!--<checklist title="抽奖时间" :options="objectList" v-model="objectListValue" @on-change="change"></checklist>-->
            <cell title="抽奖时间">
            <checker
                v-model="luck_time"
                default-item-class="time-item"
                selected-item-class="time-item-selected"
                disabled-item-class="time-item-disabled"
            >
                <checker-item v-for="i in ['3','5','8']" :key="i" :value="i">{{i}}分钟</checker-item>
            </checker>
            </cell>
            <x-button @click.native="ing">开始抽奖</x-button>
            <x-button @click.native="init">取消抽奖</x-button>
        </div>

        <div v-if="userStatus === status.__ing" >
            <div style="margin-left:60px;font-size: 25px">
                <clocker :time="downtime" slot="value">
                <!--<span class="day">%_D1</span>
                <span class="day">%_D2</span>天
                <span class="day">%_H1</span>
                <span class="day">%_H2</span>时-->距离开奖剩余
                <span class="day">%_M1</span>
                <span class="day">%_M2</span>分
                <span class="day">%_S1</span>
                <span class="day">%_S2</span>秒
                </clocker>
            </div>
            <!--<div style="position:absolute; width:100%;height:75%;overflow:scroll">
                <div v-for="player in playerArr">
                    {{player}}加入了
                </div>
            </div>-->

        </div>
        <div style="position:absolute; width:100%;height:75%;overflow:scroll">
            <div v-for="player in playerArr">
                <!--<x-img :src="player.head"></x-img>-->
                {{player}}加入了
            </div>
        </div>
        <div v-if="userStatus === status.__bomb">
            <cell title="等待开奖中..."></cell>
        </div>
        <div v-if="userStatus === status.__end">
            <!--<div v-for="lucker in owner.luckerArr">{{lucker.nick}}</div>-->
        </div>
        <div v-for="item in items">{{ item.sj }}</div>
        <div v-if="userStatus == status.__init" style="position:absolute; width:100%;height:60%;overflow:scroll">
            <x-table :cell-bordered="false" style="background-color:#fff;">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>金额</th>
                    <th>奖品</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody >
                <tr v-for="list in listArr">
                    <td>{{ list.code }}</td>
                    <td>{{ list.price }}</td>
                    <td>{{ list.prize }}</td>
                    <td>{{ list.status == 0 ? '进行中':'已结束' }}</td>
                    <!--<td v-show="false">{{ list.lottery_id }}</td>-->
                    <td><x-button mini type="primary" @click.native="showLucker(list.lottery_id)">查看</x-button></td>
                </tr>
            </tbody>
        </x-table>
        </div>
        <!--<div v-transfer-dom >
            <x-dialog style="position:relative;top:-100px;" v-model="show" hide-on-blur :dialog-style="{'max-width': '100%', width: '100%', height: '50%', 'background-color': 'transparent'}">
                <p style="color:#fff;text-align:center;" @click="show = false">
                
                <div style="margin-left:100px">
                <x-img style="width: 50px;height:50px;" src="https://o5omsejde.qnssl.com/demo/test1.jpg"></x-img>
                <x-img style="width: 50px;height:50px;" :src="img"></x-img>
                <div v-for="lucker in luckerList">
                    <x-img :src="lucker.head"></x-img>
                    昵称:{{lucker.nick}}
                </div>
                
                </div>
                <br>
                <br>
                <x-icon type="ios-close-outline" style="fill:#fff;"></x-icon>
                </p>
            </x-dialog>
        </div>-->

        <div v-transfer-dom>
            <x-dialog v-model="showScrollBox" class="dialog-demo">
                <p class="dialog-title">中奖名单</p>
                <div v-for="lucker in luckerList">
                    <x-img style="width: 40px;height:40px;" :src="lucker.head"></x-img>
                    <span style="width:50px">{{lucker.nick}}</span>
                    <x-button v-if="see && !lucker.isget" mini type="warn" @click.native="cash(lucker.details_id);lucker.isget = true">兑奖</x-button>
                    <x-button v-if="see && lucker.isget" mini type="primary">已兑奖</x-button>
                </div>
                <div @click="showScrollBox=false;see=false">
                <span class="vux-close"></span>
                </div>
            </x-dialog>
        </div>
        <!--<div v-transfer-dom >
            <x-dialog style="position:relative;top:-50px;" v-model="showScrollBox" hide-on-blur :dialog-style="{'max-width': '100%', width: '100%', height: '50%', 'background-color': 'transparent'}">
                <div v-for="i in 5">
                    <img src="http://wx.qlogo.cn/mmopen/vi_32/r9iaYia3nDPw4JN675C99UXSyssWBuNZnNp7abasd1lkB5tkgODbxWKibib1mzg86Jn08NyxafTc9lia5tKHpeVic06g/0" style="width: 40px;height:40px;">
                    {{lucker.nick}}
                    {{i}}
                </div>
                <p style="color:#fff;text-align:center;" @click="showScrollBox = false">
                <br>
                <br>
                <x-icon type="ios-close-outline" style="fill:#fff;"></x-icon>
                </p>
                
            </x-dialog>
        </div>-->
        <!--<img src="http://wx.qlogo.cn/mmopen/vi_32/r9iaYia3nDPw4JN675C99UXSyssWBuNZnNp7abasd1lkB5tkgODbxWKibib1mzg86Jn08NyxafTc9lia5tKHpeVic06g/0" style="width: 10px;height:10px;">-->
</div>

</template>

<script>
// const STATUS = 1
    import router from '../../router/router.config.js';
    import owner from '../../api/owner.js'
    import status from '../../api/status.js'
    import dateformat from 'dateformat'
    import { XImg,XDialog,TransferDomDirective as TransferDom,Cell,Checker,CheckerItem,XTable, Clocker, XButton,XInput,XNumber,Checklist } from 'vux'
    import user from '../../api/user.js'
    import qs from 'qs'
    export default {
        directives: {
            TransferDom
        },
        components: {
            XImg,
            XDialog,
            Cell,
            Checker,
            CheckerItem,
            XTable,
            Clocker,
            XButton,
            XInput,
            XNumber
        },
        router,
        data() {
            return {
                playerArr:[],
                showScrollBox:false,
                luck_time:'3',
                objectList: [{key: '3', value: '3分钟'}, {key: '5', value: '5分钟'}],
                objectListValue: ['3'],
                items: [],
                owner,
                status,
                downtime:'',
                mch_id: '',
                mch_name: '',
                price: 1,
                luck_num: 1,
                prize: '',
                title: '',
                showTime:false,
                userStatus:0,
                listArr:[],
                lottery_id:0,
                lucker:'',
                show:false,
                luckerList:[],
                see:false
            }
        },
        watch:{
            'userStatus':function(val,oldVal){
                // 如果是登录状态
                console.log("status"+val+","+oldVal)
                user.setCookie('login_status',val)
                var _ = this
                switch(val){
                    case status.__init:
                        // this.$router.push({path:'/setting'})
                        // this.$router.go(0);
                        this.playerArr = []
                        this.luck_num = 1
                        this.luck_time = '3'
                        this.prize = ''
                        this.price = 1
                        this.luckerList = []
                        // this.listHeight = 75
                        
                        break;
                    case status.__set:
                        // this.listHeight = 50
                        this.playerArr = []
                        break;
                    case status.__ing:
                        // this.playerArr = []
                        // this.listHeight = 60
                        this.downtime = dateformat(new Date(new Date().getTime()+parseInt(_.luck_time)*10000),"yyyy-mm-dd HH:MM:ss")
                        // 写入数据库
                        console.log("mch_info"+user.userinfo.mch_id+","+user.userinfo.mch_name+","+user.userinfo.openid)
                        this.$axios.post("/lottery/add",{
                            mch_id:user.userinfo.mch_id,
                            mch_name:user.userinfo.mch_name,
                            oper:user.userinfo.openid,
                            luck_num:this.luck_num,
                            luck_time:this.luck_time,
                            prize:this.prize,
                            price:this.price,
                            tag:''
                        }).then((ret)=>{
                            // console.log(ret)
                            this.lottery_id = ret.data.lottery_id
                            // console.log('lottery_id='+this.lottery_id)
                            this.listArr.reverse()
                            this.listArr.push({
                                code:ret.data.lottery_code,
                                lottery_id:ret.data.lottery_id,
                                price:this.price,
                                prize:this.prize,
                                status:0
                            })
                            this.listArr.reverse()
                            var _ = this;

                            user.socket.emit('initSubscribe',{
                                mch_id:user.userinfo.mch_id
                            })

                            // user.socket.emit('subscribe',{
                            //     mch_id:user.userinfo.mch_id,
                            //     openid:user.userinfo.openid,
                            //     tag:_.lottery_id
                            // })

                            // 监听用户加入
                            // alert(user.listened)
                            console.log(user.socket._callbacks.$joined)
                            // if(user.listened == ''){
                            if(user.socket._callbacks.$joined){
                                user.socket._callbacks.$joined = undefined
                                user.socket.on('joined',function(nick){
                                    _.playerArr.push(nick)
                                })
                            }else{
                                user.socket.on('joined',function(nick){
                                    _.playerArr.push(nick)
                                })
                            }
                            

                            // 倒计时计算
                            
                            // console.log(_.luck_num)
                            user.socket.emit('downTime',user.userinfo.mch_id,ret.data.lottery_id,_.luck_num,_.luck_time)


                            setTimeout(()=>{
                                this.userStatus = status.__bomb
                            },parseInt(_.luck_time)*10000)
                        })
                        break;
                    case status.__bomb:
                        // 开奖时刻－订阅中奖者
                        // 订阅,事件处理完得到消息
                        var _ = this;
                        // 监听通知
                        if(user.socket._callbacks.$manager_notify){
                            user.socket._callbacks.$manager_notify = undefined
                            user.socket.on('manager_notify',function(data){
                                var info = ''
                                data.forEach((el)=>{
                                    info += el.nick
                                })
                                // _.$vux.alert.show({
                                //     title: '提示',
                                //     content: info
                                // })
                                _.showScrollBox = true
                                _.luckerList = data
                                _.listArr[0].luckerArr = data

                                console.log(data)
                                // 收到通知后 取消订阅 
                                // ！如果下一句未顺利执行-后台有一个socket将不被覆盖，导致下一轮不提示的bug
                                // user.socket.emit('cancelSubscribe',{openid:user.userinfo.openid,mch_id:user.userinfo.mch_id})
                                // user.socket.emit('cancelSubscribe',{mch_id:user.userinfo.mch_id})
                                _.show = false
                            })
                        }else{
                            user.socket.on('manager_notify',function(data){
                                var info = ''
                                data.forEach((el)=>{
                                    info += el.nick
                                })
                                _.showScrollBox = true
                                _.luckerList = data
                                _.listArr[0].luckerArr = data

                                _.show = false
                            })
                        }
                        this.userStatus = status.__init
                        let len = this.listArr.length
                        this.listArr[0].status = 1 
                        break;
                    case status.__end:
                        // this.$axios.post("/lottery/close",qs.stringify({
                        //     mch_id:user.userinfo.mch_id
                        // }))
                        // .then((ret)=>{
                        //     if(ret.data.info == 9){
                        //         setTimeout(()=>{
                        //             this.init()
                        //             this.listArr.forEach((el,i)=>{
                        //                 el.status = 1
                        //             })
                        //         },5000)
                        //     }
                        // })
                        break;
                    default:
                }
            }
        },
        mounted() {
            // alert(new Date('2017-01-01 12:12:12').getTime())
            // this.userStatus = user.getCookie('login_status')
            // if(this.userStatus == undefined){
                this.userStatus = status.__init
            //     user.setCookie('login_status',status.__beigin)
            // }
            
            this.$axios.get("/lottery/getToday?mch_id="+user.userinfo.mch_id)
            .then((ret)=>{
                console.log(ret.data)
                ret.data.forEach((el,i)=>{
                    this.listArr.push({
                        lottery_id:el.lottery_id,
                        code:el.lottery_code,
                        price:el.price,
                        prize:el.prize,
                        status:el.status,
                        luckerArr:el.luckerArr
                    })
                })
                this.listArr.reverse()
                // console.log(this.listArr)
                
            })
            console.log('当前状态为',this.userStatus)
        },
        methods: {
            // test1(){
                // var DOMAIN_DOMAIN = "http://chat.ha.aoxing.aoxingtec.cn/wx_pay";
                // function initJsapi() {
                // var url = encodeURIComponent(location.href.split('#')[0]);
                // $.getJSON(DOMAIN_DOMAIN , {'url': url}, function (r) {
                    // alert(r.timeStamp)
                    // wx.chooseWXPay({
                    //     appid: 'wx4fe135a46ae46e63',
                    //     timestamp: '1509969708', // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    //     nonceStr: 'KuGXH3XFgusHH4kYn0hzH5ou4lNG5AUv', // 支付签名随机串，不长于 32 位
                    //     package: 'prepay_id=wx20171106200147dc612740c20928686362', // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    //     signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    //     paySign: '2D0842C171F49B9E0D661A9A94A20144', // 支付签名
                    //     success: function (res) {
                    //         // 支付成功后的回调函数
                    //         console.log(res)
                    //     }
                    // });
                    // {"appId":"wx4fe135a46ae46e63","timeStamp":"1509969708","nonceStr":"KuGXH3XFgusHH4kYn0hzH5ou4lNG5AUv","package":"prepay_id=wx20171106200147dc612740c20928686362","signType":"MD5","paySign":"2D0842C171F49B9E0D661A9A94A20144","timestamp":"1509969708"}
                    // wx.config({
                    //     debug: false,
                    //     appId: r.appId,
                    //     timestamp: r.timestamp,
                    //     nonceStr: r.nonceStr,
                    //     signature: r.signature,
                    //     jsApiList: [
                    //         'checkJsApi',
                    //         'scanQRCode',
                    //         'chooseWXPay'
                    //         // 'onMenuShareAppMessage'
                    //         // 所有要调用的 API 都要加到这个列表中
                    //     ]
                    // });
                    // initWxShareOption();
                // });
            // },
            cash(details_id){
                console.log(details_id)
                this.$axios.get('/lottery/cash?lottery_details_id='+details_id)
                .then((ret)=>{
                    console.log(this.luckerList)
                    this.luckerList.forEach((el)=>{
                        if(el.details_id == details_id){
                            el.isget = true
                        }
                        // el.forEach((el1)=>{
                        //     if(el1.details_id == details_id){
                        //         el1.isget = true
                        //     }
                        // })
                    })
                })
            },
            // 显示中奖者名单
            showLucker(lottery_id){
                console.log(lottery_id)
                var tmp = this.listArr.filter(el => el.lottery_id == lottery_id)
                this.luckerList = tmp[0].luckerArr
                this.see = this.showScrollBox = true
                // console.log(lottery_id)
                // this.$axios.get("/lottery/getLuckerArr?lottery_id="+lottery_id)
                // .then((ret)=>{
                //     this.luckList = ret.data
                //     this.show = true
                // })
            },
            change(val){
                console.log(val)
                // this.objectListValue = []
                // this.objectListValue.push(val)
            },
            // 默认状态
            init(){
                this.userStatus = status.__init
            },
            set(){
                this.userStatus = status.__set
            },
            ing(){
                if(this.prize == ''){
                    alert("请输入奖品名称")
                }else{
                    this.userStatus = status.__ing
                }
            },
            bomb(){
                this.userStatus = status.__bomb
            },
            end(){
                // owner.stat = status.__end
                this.userStatus = status.__begin
            },
            query(lottery_id){
                this.$axios.get("/lottery/getLuckerArr?lottery_id=" + lottery_id)
                .then((ret)=>{
                    console.log(ret)
                })
            },
            test(){
                // this._getWxpayData()
                // window.location.href="/user/pay";
            },
            _getWxpayData() {
                this.$axios.get('/lottery/wxpay?openid=' + 'opxwxw9i2-AtcYCNqY6YNmu5ugkg').then((res) => {
                // 这里的openid我存在了localStorage里面，获取授权进入时就进行了一次存入，方便调用。
                    console.log(res)
                    res = res.data
                    console.log(res)
                    if (res.status === 1) {
                        console.log('434:yes')
                        this._wxpayConfig()
                        wx.ready(() => {
                            this._setWxpayInfo(res.data)
                        })
                    }
                })
            },
            _wxpayConfig() {
                this.$axios.get('/lottery/signa').then((res) => {
                    console.log(res.body)
                    // let data = res.body.data
                    let data = res.data
                    // if (res.body.status === 1) {
                    if (data.status === 1) {
                        alert('config')
                        wx.config({
                            // debug: true,
                            appId: data.appId,
                            timestamp: data.timestamp,
                            nonceStr: data.nonceStr,
                            signature: data.signature,
                            jsApiList: ['chooseWXPay']
                        })
                    }
                })
            },
            _setWxpayInfo(data) {
                console.log('pay')
                wx.chooseWXPay({
                    appId: data.appId,
                    timestamp: data.timeStamp,
                    nonceStr: data.nonceStr,
                    package: data.package,
                    signType: data.signType,
                    paySign: data.paySign,
                    success(res) {
                        if (res.errMsg === 'chooseWXPay:ok') {
                            window.alert('支付成功')
                            window.location.reload()
                        } else {
                            window.alert(' 支付失败')
                            window.location.reload()
                        }
                    },
                    cancel() {
                        window.alert('支付取消')
                        window.location.reload()
                    },
                    error(res) {
                        window.alert('支付失败')
                        window.location.reload()
                    }
                })
            }
        }
    }
</script>

<style lang="less" scoped>
    .vux-close {
    position: relative;
    display: inline-block;
    vertical-align: middle;
    color: #999;
    width: 24px;
    height: 24px;
    &:before,
    &:after {
        content: '';
        position: absolute;
        left: 0;
        top: 11px;
        width: 24px;
        height: 1px;
        background-color: currentColor;
        transform: rotate(-45deg);
    }
    &:after {
        transform: rotate(45deg);
    }
    }

    input{
        border: 1px solid black
    }
    .day {
        background-color:#000;
        color:#fff;
        text-align:center;
        display:inline-block;
        padding:0 3px;
        border-radius:3px;
    }
    .time-item {
        width: 100px;
        height: 26px;
        line-height: 26px;
        text-align: center;
        border-radius: 3px;
        border: 1px solid #ccc;
        background-color: #fff;
        margin-right: 26px;
    }
    .time-item-selected {
        border-color: #ff4a00;
    }
    .time-item-disabled {
        color: #999;
    }
    /*.dialog-demo {
    .weui-dialog{
        border-radius: 8px;
        padding-bottom: 8px;
    }
    .dialog-title {
        line-height: 30px;
        color: #666;
    }
    .img-box {
        height: 350px;
        overflow: hidden;
    }
    .vux-close {
        margin-top: 8px;
        margin-bottom: 8px;
    }
    }*/
    .dialog-demo {
  .weui-dialog{
    border-radius: 8px;
    padding-bottom: 8px;
  }
  .dialog-title {
    line-height: 30px;
    color: #666;
  }
  .img-box {
    height: 350px;
    overflow: hidden;
  }
  .vux-close {
    margin-top: 8px;
    margin-bottom: 8px;
  }
}
</style>